package rstplus;

/*
 * RST - Russian SMS transliterator
 * Copyleft 2011
 * Author: Alexey Shat'ko (Алексей Шатько), rstapp@yandex.ru
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this source code (in file copying.txt); if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */


import java.io.*;
import java.util.Enumeration;
import java.util.Vector;
import javax.microedition.rms.*;

public final class DraftStorage {

    private static final String RS_NAME = "rstplus.draft";
    private static RecordStore rs = null;
    private static int rsOpen = 0;

    public static String read() throws RecordStoreException {
        byte[] record = null;
        rsOpen();
        try {
            RecordEnumeration re = rs.enumerateRecords(null, null, false);
            try {
                if (re.hasNextElement()) {
                    record = re.nextRecord();
                    if (re.hasNextElement()) {
                        throw new RecordStoreException();
                    }
                }
            } finally {
                re.destroy();
            }
        } finally {
            rsClose();
        }
        if (record == null) {
            return "";
        } else {
            try {
                DataInputStream dis = new DataInputStream(new ByteArrayInputStream(record));
                try {
                    return dis.readUTF();
                } finally {
                    dis.close();
                }
            } catch (Exception exc) {
                return "";
            }
        }
    }

    public static void set(String text) throws RecordStoreException {
        if ((text == null) || (text.equals(""))) {
            Vector v = new Vector();
            rsOpen();
            try {
                RecordEnumeration re = rs.enumerateRecords(null, null, false);
                try {
                    while (re.hasNextElement()) {
                        v.addElement(new Integer(re.nextRecordId()));
                    }
                } finally {
                    re.destroy();
                }
                Enumeration ids = v.elements();
                while (ids.hasMoreElements()) {
                    rs.deleteRecord(((Integer) ids.nextElement()).intValue());
                }
            } finally {
                rsClose();
            }
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(baos);
            try {
                try {
                    dos.writeUTF(text);
                } finally {
                    dos.close();
                }
            } catch (Exception exc) {
                throw new RuntimeException();
            }
            byte[] record = baos.toByteArray();
            rsOpen();
            try {
                int id = -1;
                RecordEnumeration re = rs.enumerateRecords(null, null, false);
                try {
                    if (re.hasNextElement()) {
                        id = re.nextRecordId();
                        if (re.hasNextElement()) {
                            throw new RecordStoreException();
                        }
                    }
                } finally {
                    re.destroy();
                }
                if (id < 0) {
                    rs.addRecord(record, 0, record.length);
                } else {
                    rs.setRecord(id, record, 0, record.length);
                }
            } finally {
                rsClose();
            }
        }
    }

    private static void rsOpen() throws RecordStoreException {
        if (rsOpen <= 0) {
            rs = RecordStore.openRecordStore(RS_NAME, true);
            rsOpen = 1;
        } else {
            rsOpen++;
        }
    }

    private static void rsClose() throws RecordStoreException {
        if (rsOpen > 1) {
            rsOpen--;
        } else if (rsOpen == 1) {
            rs.closeRecordStore();
            rs = null;
            rsOpen = 0;
        }
    }
}
